import Constants from './Constants';
import { message } from 'antd';
import reqwest from 'reqwest';

const R = require('ramda');

export function formatMobile(mobile) {
    var reg = /^[0-9]{11,20}$/;
    if (reg.exec(mobile)) {
        return mobile.substring(0, 3) + '-' + mobile.substring(3, 7) + '-' + mobile.substring(7, 11)
    }
    return mobile;
}

export function download(url, conditions) {
    let conditionsStr = "";
    let _url = url;
    if (conditions) {
        for (let p in conditions) {
            if (conditions[p]) conditionsStr += (p + "=" + conditions[p] + "&");
        }
    }

    conditionsStr += Constants.ACJSESSIONID + "=" + sessionStorage.getItem(Constants.ACJSESSIONID);
    if (conditionsStr !== "") _url += ("?" + conditionsStr);
    message.info("请耐心等待下载...");
    window.location.href = encodeURI(_url);
}
/**
 * 
 * @param {*} mol 模块
 * @param {*} code 系统编码
 * @param {*} url 
 */
export function downloadFile({ mol, code, url }) {
    if (mol && code && url) {
        let fileName = encodeURI(encodeURI(url.substring(url.lastIndexOf('/') + 1, url.length)));
        let fileUrl = apiPath.mc + "/api/file/" + mol + "/download/" + code + "?fileName=" + fileName
        let downUrl = fileUrl + "&" + Constants.ACJSESSIONID + "=" + sessionStorage.getItem(Constants.ACJSESSIONID);
        window.location.href = downUrl;
    } else {
        message.info("下载参数错误");
    }

}

export function convertOrganizations(node) {
    let newNode = {
        label: node.orgName,
        value: node.orgId + "",
        key: node.orgId + "",
        children: node.children && node.children.length > 0 ? node.children.map(treeNode => convertOrganizations(treeNode)) : []
    };
    return newNode;
};

/**
 * 文件上传共用方法
 * @param module: 文件上传的业务类型，例如supplier    
 * @param id: 上传实体所对应的
 * @param data: 文件列表
 */
export function fileUpload({ modules, id, data, onSuccess, onFail, successMsg, failMsg }) {
    if (!modules || !id || !data) return;
    message.info("文件上传中，请耐心等待...");
    let { UPLOAD_PREFIX, UPLOAD_TEXT } = Constants.FILE;
    let url = UPLOAD_PREFIX + modules + UPLOAD_TEXT + id;
    const formData = new FormData();
    data.forEach((file) => {
        formData.append('file', file);
    });
    reqwest({
        url,
        method: 'post',
        processData: false,
        data: formData,
        headers: { [Constants.ACJSESSIONID]: sessionStorage.getItem(Constants.ACJSESSIONID) },
        success: () => {
            if (onSuccess) onSuccess();
            message.success(successMsg ? successMsg : '文件上传成功');
        },
        error: () => {
            if (onFail) onFail();
            message.error(failMsg ? failMsg : '文件上传失败，请稍后再试');
        },
    });
}

/**
 * 跟单补料文件上传方法 
 * @param orderId: 上传实体所对应的
 * @param data: 文件列表
 */
export function siFileUpload({ orderId, data, onSuccess, onFail, successMsg, failMsg }) {
    if (!orderId || !data) return;
    message.info("文件解析中，请耐心等待...");
    let { UPLOAD_SI } = Constants.FILE;
    let url = UPLOAD_SI + orderId;
    const formData = new FormData();
    data.forEach((file) => {
        formData.append('file', file);
    });
    reqwest({
        url,
        method: 'post',
        processData: false,
        data: formData,
        headers: { [Constants.ACJSESSIONID]: sessionStorage.getItem(Constants.ACJSESSIONID) },
        success: (data) => {
            if (data && data.resultCode === "ok") {
                if (onSuccess) onSuccess();
                message.success(successMsg ? successMsg : '文件解析成功');
            } else {
                if (onFail) onFail();
                message.error(failMsg ? failMsg : '文件解析失败，请稍后再试');
            }
        },
        error: () => {
            if (onFail) onFail();
            message.error(failMsg ? failMsg : '文件解析失败，请稍后再试');
        },
    });
}

/**
 * 存在非法字符返回false
 * @param {*} str 要校验的字符串
 * @param {*} specialKey 特殊字符的集合,例如："#+&"
 */

export function checkIllegalChar(str, specialKey) {
    for (var i = 0; i < str.length; i++) {
        if (specialKey.indexOf(str.substr(i, 1)) != -1) {
            return false;
        }
    }
    return true;
}

export function pageObjGenerator(page, url, condition, dispatch, onSuccess) {
    return {
        showTotal: total => `共 ${total} 条数据`,
        pageSize: page.size,
        current: page.page,
        total: page.totalRow,
        showSizeChanger: true,
        onShowSizeChange: (current, size) => {
            let newPage = R.pick(['page', 'size'], page);
            newPage.size = size;
            newPage.page = 1;
            dispatch({
                type: url,
                payload: {
                    ...condition,
                    ...newPage,
                    onSuccess: onSuccess
                }
            });
        },
        onChange: (pageNumber, pageSize) => {
            let newPage = R.pick(['page', 'size'], page);
            newPage.page = pageNumber;
            dispatch({
                type: url,
                payload: {
                    ...condition,
                    ...newPage,
                    onSuccess: onSuccess
                }
            });
        }
    }
}

/**
 * 批量导入
 * @param module: 上传实体所对应的
 * @param data: 文件
 */
export function importData({ modules, data, onSuccess, onFail, successMsg, failMsg }) {
    if (!modules || !data) return;
    message.info("文件上传中，请耐心等待...");
    let { IMPORT_DATA } = Constants.FILE;
    let url = IMPORT_DATA + modules;
    const formData = new FormData();
    data.forEach((file) => {
        formData.append('file', file);
    });
    reqwest({
        url,
        method: 'post',
        processData: false,
        data: formData,
        headers: { [Constants.ACJSESSIONID]: sessionStorage.getItem(Constants.ACJSESSIONID) },
        success: (data) => {
            if (data && data.resultCode === "ok") {
                if (onSuccess) onSuccess();
                message.success(successMsg ? successMsg : '文件导入成功');
            } else {
                if (onFail) onFail();
                message.error(failMsg ? failMsg : '文件导入失败，请稍后再试!');
            }
        },
        error: () => {
            if (onFail) onFail();
            message.error(failMsg ? failMsg : '文件导入失败，请稍后再试!');
        },
    });
}

/**
 * 自定义分页  根据分页对象以及总的list返回分页后的list
 * @param page
 * @param list
 */
export function genneatePageList(page, list) {
    let result = [];
    if (!page || !list) return result;
    if (list.length === 0) return result;
    if (!page.page || page.page < 1) return result;
    if (!page.size || page.size < 1) return result;
    list.map((item, index) => {
        if (index >= (page.page - 1) * page.size && index < page.page * page.size) result.push(item);
    })
    return result;
}